 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=155 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Using preferences
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='GeneralLookPreferencesEditor,preferences,swing,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Using preferences</div>

<div class='main-body'>
 
<br>The <a href="http://java.sun.com/j2se/1.4.2/docs/guide/lang/preferences.html">Preferences
API</a> is not part of Swing, but is often used in graphical applications.
It provides a lightweight and simple way of storing application and user
preferences, without directly accessing the file system or using JNDI.

<p><b>Example</b>

<p>Here, the Preferences API is used to store and access user preferences
related to the general look and feel of an application:
<ul>
<li>
toolbar visiblilty</li>

<li>
icon size</li>

<li>
colors and fonts</li>
</ul>
Note the field <tt>fPrefs</tt>, and the pairs of keys and default values
for each preference.
<br>
<PRE>

<span class='keyword'>package</span> hirondelle.stocks.preferences;

<span class='keyword'>import</span> java.util.*;
<span class='keyword'>import</span> java.util.logging.*;
<span class='keyword'>import</span> java.awt.*;
<span class='keyword'>import</span> java.awt.event.*;
<span class='keyword'>import</span> javax.swing.*;
<span class='keyword'>import</span> java.util.prefs.*;
<span class='keyword'>import</span> javax.swing.plaf.metal.MetalTheme;

<span class='keyword'>import</span> hirondelle.stocks.util.ui.Theme;
<span class='keyword'>import</span> hirondelle.stocks.util.ui.UiConsts;
<span class='keyword'>import</span> hirondelle.stocks.util.ui.UiUtil;
<span class='keyword'>import</span> hirondelle.stocks.util.Util;

<span class='comment'>/**
* Allows editing of user preferences related to the general 
* appearance of the application, such as font size, toolbar icon size, theme, 
* and the like.
*
* &lt;P&gt;Also allows programmatic read-only access to the current stored preferences 
* for these items.
*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> GeneralLookPreferencesEditor <span class='keyword'>extends</span> Observable 
  <span class='keyword'>implements</span> PreferencesEditor {

  <span class='keyword'>public</span> JComponent getUI(){
    JPanel content = <span class='keyword'>new</span> JPanel();
    GridBagLayout gridbag = <span class='keyword'>new</span> GridBagLayout();
    content.setLayout(gridbag);
    
    addShowToolbarAndLargeIcons(content);
    addTheme(content);
    addRestoreDefaults(content);
    UiUtil.addVerticalGridGlue(content, <span class='literal'>4</span>);
    
    matchGuiToStoredPrefs();
    <span class='keyword'>return</span> content;
  }
  
  <span class='keyword'>public</span> String getTitle() {
    <span class='keyword'>return</span> TITLE;
  }
  
  <span class='keyword'>public</span> <span class='keyword'>int</span> getMnemonic() {
    <span class='keyword'>return</span> MNEMONIC;
  }

  <span class='keyword'>public</span> <span class='keyword'>void</span> savePreferences(){
    fLogger.fine(<span class='literal'>"Updating general preferences."</span>);
    fPrefs.putBoolean(SHOW_TOOL_BAR_KEY, fShowToolBar.isSelected());
    fPrefs.putBoolean(USE_LARGE_ICONS, fLargeIcons.isSelected());
    fPrefs.put(THEME_NAME_KEY, fThemes.getSelectedItem().toString());
    setChanged();
    notifyObservers();
  }

  <span class='keyword'>public</span> <span class='keyword'>void</span> matchGuiToDefaultPreferences(){
    fShowToolBar.setSelected(SHOW_TOOLBAR_DEFAULT);
    fLargeIcons.setSelected(USE_LARGE_ICONS_DEFAULT);
    fThemes.setSelectedItem( Theme.valueOf(THEME_NAME_DEFAULT) );
  }

  <span class='comment'>/**
  * Return the stored user preference for hiding or showing the toolbar.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>boolean</span> hasShowToolBar(){
    <span class='keyword'>return</span> fPrefs.getBoolean(SHOW_TOOL_BAR_KEY, SHOW_TOOLBAR_DEFAULT);
  }
  
  <span class='comment'>/**
  * Return the stored user preference for using large icons.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>boolean</span> hasLargeIcons(){
    <span class='keyword'>return</span> fPrefs.getBoolean(USE_LARGE_ICONS, USE_LARGE_ICONS_DEFAULT);
  }
  
  <span class='comment'>/**
  * Return the stored user preference for the theme to be applied to the Java 
  * look-and-feel.
  */</span>
  <span class='keyword'>public</span> MetalTheme getTheme(){
    String themeName = fPrefs.get(THEME_NAME_KEY, THEME_NAME_DEFAULT);
    <span class='keyword'>return</span> Theme.valueOf(themeName);
  }
  
  <span class='comment'>// PRIVATE //
</span>
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String GENERAL_LOOK_NODE = <span class='literal'>"stocksmonitor/ui/prefs/GeneralLook"</span>;
  <span class='keyword'>private</span> Preferences fPrefs = Preferences.userRoot().node(GENERAL_LOOK_NODE);

  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String TITLE = <span class='literal'>"General Look"</span>;
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> <span class='keyword'>int</span> MNEMONIC = KeyEvent.VK_G;
  
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> <span class='keyword'>boolean</span> SHOW_TOOLBAR_DEFAULT = <span class='keyword'>true</span>;
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String SHOW_TOOL_BAR_KEY = <span class='literal'>"ShowToolbar"</span>;

  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> <span class='keyword'>boolean</span> USE_LARGE_ICONS_DEFAULT = <span class='keyword'>false</span>;
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String USE_LARGE_ICONS = <span class='literal'>"UseLargeIcons"</span>;

  <span class='comment'>//Theme name is mapped to Theme using Theme.valueOf
</span>  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String THEME_NAME_DEFAULT = <span class='literal'>"Default"</span>;
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String THEME_NAME_KEY = <span class='literal'>"ThemeName"</span>;

  <span class='keyword'>private</span> JCheckBox fShowToolBar;
  <span class='keyword'>private</span> JCheckBox fLargeIcons;
  <span class='keyword'>private</span> JComboBox fThemes;
  
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> Logger fLogger = Util.getLogger(GeneralLookPreferencesEditor.<span class='keyword'>class</span>);
  
  <span class='keyword'>private</span> <span class='keyword'>void</span> matchGuiToStoredPrefs(){
    fShowToolBar.setSelected( hasShowToolBar() );
    fLargeIcons.setSelected( hasLargeIcons() );
    fThemes.setSelectedItem( getTheme() );
  }
  
  <span class='keyword'>private</span> <span class='keyword'>void</span> addShowToolbarAndLargeIcons(JPanel aContent){
    JLabel toolbar = <span class='keyword'>new</span> JLabel(<span class='literal'>"Show:"</span>);
    aContent.add( toolbar, getConstraints(<span class='literal'>0</span>,<span class='literal'>0</span>) );
    
    fShowToolBar = <span class='keyword'>new</span> JCheckBox(<span class='literal'>"Toolbar"</span>);
    fShowToolBar.setMnemonic(KeyEvent.VK_O);
    aContent.add( fShowToolBar, getConstraints(<span class='literal'>0</span>,<span class='literal'>1</span>) );
    
    JLabel iconSize = <span class='keyword'>new</span> JLabel(<span class='literal'>"Icon Size:"</span>);
    aContent.add( iconSize, getConstraints(<span class='literal'>1</span>,<span class='literal'>0</span>) );

    fLargeIcons = <span class='keyword'>new</span> JCheckBox(<span class='literal'>"Use Large Icons"</span>);
    fLargeIcons.setMnemonic(KeyEvent.VK_U);
    iconSize.setLabelFor( fLargeIcons );
    aContent.add( fLargeIcons, getConstraints(<span class='literal'>1</span>,<span class='literal'>1</span>) );
  }

  <span class='keyword'>private</span> <span class='keyword'>void</span> addTheme(JPanel aContent) {
    JLabel theme = <span class='keyword'>new</span> JLabel(<span class='literal'>"Theme:"</span>);
    theme.setDisplayedMnemonic(KeyEvent.VK_T);
    aContent.add( theme, getConstraints(<span class='literal'>2</span>,<span class='literal'>0</span>) );
    
    DefaultComboBoxModel themesModel = <span class='keyword'>new</span> DefaultComboBoxModel( Theme.VALUES.toArray());
    fThemes = <span class='keyword'>new</span> JComboBox(themesModel);
    theme.setLabelFor( fThemes );
    aContent.add( fThemes, getConstraints(<span class='literal'>2</span>,<span class='literal'>1</span>) );
  }

  <span class='keyword'>private</span> <span class='keyword'>void</span> addRestoreDefaults(JPanel aContent) {
    JButton restore = <span class='keyword'>new</span> JButton(<span class='literal'>"Restore Defaults"</span>);
    restore.setMnemonic(KeyEvent.VK_D);
    restore.addActionListener( <span class='keyword'>new</span> ActionListener() {
      <span class='keyword'>public</span> <span class='keyword'>void</span> actionPerformed( ActionEvent event ) {
        matchGuiToDefaultPreferences();
      }
    });
    GridBagConstraints constraints = UiUtil.getConstraints(<span class='literal'>3</span>,<span class='literal'>1</span>);
    constraints.insets = <span class='keyword'>new</span> Insets(UiConsts.ONE_SPACE, <span class='literal'>0</span>,<span class='literal'>0</span>,<span class='literal'>0</span>);
    aContent.add( restore, constraints );
  }
  
  <span class='keyword'>private</span> GridBagConstraints getConstraints(<span class='keyword'>int</span> aY, <span class='keyword'>int</span> aX){
    GridBagConstraints result = UiUtil.getConstraints(aY, aX);
    result.insets = <span class='keyword'>new</span> Insets(<span class='literal'>0</span>, <span class='literal'>0</span>, UiConsts.ONE_SPACE, UiConsts.ONE_SPACE);
    <span class='keyword'>return</span> result;
  }
}
 
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicAction7009-2.html?Id=154'>Preferences dialogs</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='155'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=155 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
